package com.koron.common.core.business.langfield.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.business.langfield.bean.LangFieldBean;
import com.koron.common.core.business.langfield.bean.LangFormBean;
import com.koron.common.core.business.langfield.bean.LangFormTreeVo;
import com.koron.common.core.business.langfield.mapper.LangFieldBeanMapper;
import com.koron.common.core.business.langfield.mapper.LangFormBeanMapper;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.CommonUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LangFormService {

    @TaskAnnotation("addLangForm")
    public Response addLangForm(SessionFactory factory, LangFormBean langformbean) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);

        // 1. 同一数据字典分类下，字典编码不能重复
        List<LangFormBean> list = mapper.queryByFormKey(langformbean.getFormKey(), null);
        Assert.isFalse(CollUtil.isNotEmpty(list), "同分类下表单不能重复");

        langformbean.setId(CodeTools.getCode32());
        mapper.insert(langformbean);
        return Response.success();
    }

    @TaskAnnotation("removeLangForm")
    public Response removeLangForm(SessionFactory factory, String id) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);
        LangFieldBeanMapper langfieldbeanmapper = factory.getMapper(LangFieldBeanMapper.class);

        List<LangFieldBean> detlist = langfieldbeanmapper.queryByParentId(id, null);
        Assert.isFalse(CollUtil.isNotEmpty(detlist), "请先清除表单字段");

        mapper.deleteByPrimaryKey(id);
        return Response.success();
    }

    @TaskAnnotation("updateLangForm")
    public Response updateLangForm(SessionFactory factory, LangFormBean langformbean) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);
        Assert.isFalse(StrUtil.isBlank(langformbean.getId()), "表单id不能为空");

        // 1. 同一数据字典分类下，字典编码不能重复
        List<LangFormBean> list = mapper.queryByFormKey(langformbean.getFormKey(), langformbean.getId());
        Assert.isFalse(CollUtil.isNotEmpty(list), "同分类下表单不能重复");

        mapper.updateByPrimaryKey(langformbean);
        return Response.success();
    }

    @TaskAnnotation("queryDet")
    public Response queryDet(SessionFactory factory, String id, String formKey, String fieldKey,String lang, PageQuery query) {
        LangFieldBeanMapper langfieldbeanmapper = factory.getMapper(LangFieldBeanMapper.class);

        if (ObjectUtil.isNotNull(query)) {
            PageHelper.startPage(query.getPage(), query.getPageSize(), query.getOrderBy());
        }

        List<LangFieldBean> detlist = new ArrayList<>();
        if (StrUtil.isNotBlank(fieldKey)) {
            detlist = langfieldbeanmapper.queryByParentIdAndFieldKey(id,fieldKey);
        }else if (StrUtil.isNotBlank(id)) {
            detlist = langfieldbeanmapper.queryByParentId(id, lang);
        }
        return Response.success(new PageInfo(detlist));
    }

    @TaskAnnotation("fieldTreeBuild")
    public Response treeBuild(SessionFactory factory) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);
        List<LangFormTreeVo> langFormTreeVos = mapper.queryTree(null);
        return Response.success(langFormTreeVos);
    }

    @TaskAnnotation("queryByClassifyId")
    public Response queryByClassifyId(SessionFactory factory, String classifyId, String formName, PageQuery query) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);

        if (ObjectUtil.isNotNull(query)) {
            PageHelper.startPage(query.getPage(), query.getPageSize(), query.getOrderBy());
        }

        List<LangFormBean> det = mapper.queryByClassifyId(classifyId, formName);
        return Response.success(new PageInfo(det));
    }

    @TaskAnnotation("jsonExport")
    public Response jsonExport(SessionFactory factory, List<String> ids) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);
        List<LangFormBean> langFormTreeVos = mapper.queryAllTree(ids);
        return Response.success(langFormTreeVos);
    }


    @TaskAnnotation("jsonImp")
    public Response jsonImp(SessionFactory factory, String classifyId, List<LangFormBean> dtolist) {
        LangFormBeanMapper mapper = factory.getMapper(LangFormBeanMapper.class);
        LangFieldBeanMapper langfieldbeanmapper = factory.getMapper(LangFieldBeanMapper.class);

        Assert.isFalse(CollUtil.isEmpty(dtolist), "json不能为空");

        List<String> formkeylist = dtolist.stream().map(LangFormBean::getFormKey).collect(Collectors.toList());
        List<String> duplicateFormlist = CommonUtils.getDuplicateElements(formkeylist);
        if (CollUtil.isNotEmpty(duplicateFormlist)) {
            Assert.isFalse(true, StrUtil.format("{}表单重复", duplicateFormlist.get(0)));
        }

        for (LangFormBean langFormBean : dtolist) {
            List<String> duplicateFieldlist = langFormBean.getChildren().stream().map(LangFieldBean::getFieldKey).collect(Collectors.toList());
            List<String> duplicateElements = CommonUtils.getDuplicateElements(duplicateFieldlist);
            if (CollUtil.isNotEmpty(duplicateElements)) {
                Assert.isFalse(true, StrUtil.format("{}表单{}字段重复", langFormBean.getFormKey(), duplicateElements.get(0)));
            }
        }

        dtolist.stream().forEach(d -> {
            List<LangFieldBean> children = d.getChildren();
            if (CollUtil.isNotEmpty(children)) {
                List<String> fieldKeylist = children.stream().map(LangFieldBean::getFieldKey).collect(Collectors.toList());
                List<String> duplicateFieldlist = CommonUtils.getDuplicateElements(fieldKeylist);
                Assert.isFalse(CollUtil.isNotEmpty(duplicateFieldlist),
                        StrUtil.format("{}表单中{}字段重复"), d.getFormKey(), CollUtil.join(duplicateFieldlist, "、"));
            }
        });

        // 分类下所有表单
        List<LangFormBean> dbformlist = mapper.queryByClassifyId(classifyId, null);
        Map<String, LangFormBean> formIdObjecmap = dbformlist.stream().collect(Collectors.toMap(LangFormBean::getFormKey, item -> item));
        List<String> dbformkeylist = dbformlist.stream().map(LangFormBean::getFormKey).collect(Collectors.toList());

        // 分类下所有字段
        List<LangFieldBean> dbdetlist = langfieldbeanmapper.queryFireldByClassifyId(classifyId);

        // 表单-字段map
        Map<String, List<LangFieldBean>> formmap = new HashMap();
        if (CollUtil.isNotEmpty(dbdetlist)) {
            formmap = dbdetlist.stream().filter(f -> StrUtil.isNotBlank(f.getFormKey())).collect(Collectors.groupingBy(LangFieldBean::getFormKey));
        }

        List<LangFormBean> forminsertlist = new ArrayList();
        List<LangFormBean> formupdatelist = new ArrayList();

        List<LangFieldBean> fieldinsertlist = new ArrayList();
        List<LangFieldBean> fieldlupdetaist = new ArrayList();

        for (LangFormBean dtoFormBean : dtolist) {
            String formKey = dtoFormBean.getFormKey();
            List<LangFieldBean> children = dtoFormBean.getChildren();
            // 表单是否存在已存在
            boolean formexist = dbformkeylist.contains(formKey);
            if (formexist) {
                LangFormBean oldForm = formIdObjecmap.get(formKey);
                // 赋值原有id
                dtoFormBean.setId(oldForm.getId());
                dtoFormBean.setClassifyId(classifyId);
                // 表单已存在的字段
                List<LangFieldBean> langFieldBeans = formmap.get(formKey);
                Map<String, String> fieldIdmap = new HashMap<>();
                if (CollUtil.isNotEmpty(langFieldBeans)) {
                    fieldIdmap = langFieldBeans.stream().collect(Collectors.toMap(LangFieldBean::getFieldKey, LangFieldBean::getId));
                }
                for (LangFieldBean child : children) {
                    // 字段是否已存在
                    boolean fieldexist = fieldIdmap.keySet().contains(child.getFieldKey());
                    if (fieldexist) {
                        child.setParentId(oldForm.getId());
                        child.setId(fieldIdmap.get(child.getFieldKey()));
                        fieldlupdetaist.add(child);
                    } else {
                        child.setId(CodeTools.getCode32());
                        child.setParentId(oldForm.getId());
                        child.setFormKey(formKey);
                        fieldinsertlist.add(child);
                    }
                }
                formupdatelist.add(dtoFormBean);
            } else {
                dtoFormBean.setId(CodeTools.getCode32());
                dtoFormBean.setClassifyId(classifyId);
                for (LangFieldBean child : children) {
                    child.setId(CodeTools.getCode32());
                    child.setParentId(dtoFormBean.getId());
                    child.setFormKey(formKey);
                    fieldinsertlist.add(child);
                }
                forminsertlist.add(dtoFormBean);
            }

        }

        // 遍历导入的jsonArray
//        for (LangFormBean dtoFormBean : dtolist) {
//            List<LangFieldBean> children = dtoFormBean.getChildren();
//            if (StrUtil.isBlank(dtoFormBean.getId())) {
//                Assert.isFalse(dbformkeylist.contains(dtoFormBean.getFormKey()), StrUtil.format("{}表单重复", dtoFormBean.getFormKey()));
//                dtoFormBean.setId(CodeTools.getCode32());
//                dtoFormBean.setClassifyId(classifyId);
//                if (CollUtil.isNotEmpty(children)) {
//                    for (LangFieldBean child : children) {
//                        child.setId(CodeTools.getCode32());
//                        child.setParentId(dtoFormBean.getId());
//                        child.setFormKey(dtoFormBean.getFormKey());
//                        fieldinsertlist.add(child);
//                    }
//                }
//                forminsertlist.add(dtoFormBean);
//            } else {
//                dtoFormBean.setClassifyId(classifyId);
//                boolean repeatForm = dbformlist.stream().anyMatch(f -> !f.getId().equals(dtoFormBean.getId()) && f.getFormKey().equals(dtoFormBean.getFormKey()));
//                Assert.isFalse(repeatForm, StrUtil.format("{}表单重复", dtoFormBean.getFormKey()));
//                formupdatelist.add(dtoFormBean);
//                if (CollUtil.isEmpty(children)) {
//                    continue;
//                }
//                for (LangFieldBean child : children) {
//                    if (StrUtil.isBlank(child.getId())) {
//                        child.setId(CodeTools.getCode32());
//                        child.setParentId(dtoFormBean.getId());
//                        child.setFormKey(dtoFormBean.getFormKey());
//                        fieldinsertlist.add(child);
//                    } else {
//                        Assert.isFalse(StrUtil.isBlank(child.getFormKey()), "{}表单{}字段表单标识不能为空", dtoFormBean.getFormKey(), child.getFieldKey());
//                        List<LangFieldBean> langFieldBeans = formmap.get(child.getFormKey());
//                        boolean repeatField = langFieldBeans.stream().anyMatch(f -> !f.getId().equals(child.getId()) && f.getFieldKey().equals(child.getFieldKey()));
//                        Assert.isFalse(repeatField, StrUtil.format("{}表单{}字段重复", dtoFormBean.getFormKey(), child.getFieldKey()));
//                        fieldlupdetaist.add(child);
//                    }
//                }
//            }
//        }

        Lists.partition(forminsertlist, 300).stream().forEach(p -> {
            mapper.batchInsert(p);
        });
        Lists.partition(fieldinsertlist, 300).stream().forEach(p -> {
            langfieldbeanmapper.batchInsert(p);
        });

        Lists.partition(formupdatelist, 300).stream().forEach(p -> {
            mapper.updateBatchSelective(p);
        });
        Lists.partition(fieldlupdetaist, 300).stream().forEach(p -> {
            langfieldbeanmapper.updateBatchSelective(p);
        });

        return Response.success();
    }
}